package com.htgd.gardenexpo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.GeConDailyDataDeckTaskMapper;
import com.htgd.gardenexpo.dao.GeConSportsMaxMapper;
import com.htgd.gardenexpo.dao.WxUserDao;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.dao.GeConDailyDataDeckMapper;
import com.htgd.gardenexpo.service.IGeConDailyDataDeckService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htgd.gardenexpo.service.IGeConWeatherService;
import com.htgd.gardenexpo.utils.WeatherUtils;
import com.htgd.gardenexpo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.htgd.gardenexpo.utils.CalculationUtils.getSpeed;
import static com.htgd.gardenexpo.utils.CommonUtils.*;
import static com.htgd.gardenexpo.utils.DateUtils.getDayOfWeek;
import static com.htgd.gardenexpo.utils.DateUtils.getWeekDate;
import static com.htgd.gardenexpo.utils.SportsUtils.calculateCalories;
import static com.htgd.gardenexpo.utils.TimeUtils.formatMinutesToTime;
import static com.htgd.gardenexpo.utils.TimeUtils.formatSecondsToTime;

/**
 * <p>
 * 日常甲板数据 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-03
 */
@Service
public class GeConDailyDataDeckServiceImpl extends ServiceImpl<GeConDailyDataDeckMapper, GeConDailyDataDeck> implements IGeConDailyDataDeckService {

    @Autowired
    private GeConDailyDataDeckMapper geConDailyDataDeckMapper;

    @Autowired
    private WxUserDao wxUserDao;

    @Autowired
    private IGeConWeatherService geConWeatherService;

    @Autowired
    private WeatherUtils weatherUtils;

    @Autowired
    private GeConSportsMaxMapper geConSportsMaxMapper;

    @Autowired
    private GeConDailyDataDeckTaskMapper geConDailyDataDeckTaskMapper;


    @Override
    public CommonResult add(GeConDailyDataDeck geConDailyDataDeck) {
        //新建任务
        GeConDailyDataDeckTask geConDailyDataDeckTask = geConDailyDataDeckTaskMapper.selectById(geConDailyDataDeck.getTaskId());
        if(geConDailyDataDeckTask==null){
            GeConDailyDataDeckTask geConDailyDataDeckTask1 = new GeConDailyDataDeckTask();
            geConDailyDataDeckTask1.setDeckId(geConDailyDataDeck.getDeckId());
            geConDailyDataDeckTask1.setId(geConDailyDataDeck.getTaskId());
            geConDailyDataDeckTask1.setStatus("1");
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime dateTime = LocalDateTime.parse(geConDailyDataDeck.getBeginTime(), formatter);
            geConDailyDataDeckTask1.setBeginTime(dateTime);
            geConDailyDataDeckTaskMapper.insert(geConDailyDataDeckTask1);
        }
        //卡路里
        WxUser wxUser = wxUserDao.getByDeckId(geConDailyDataDeck.getDeckId());
        double calorie = 0d;
        if(wxUser!=null){
            if(wxUser.getWeight()!=null) {
                calorie = calculateCalories(geConDailyDataDeck.getMileage(), wxUser.getWeight());
            }else {
                calorie = calculateCalories(geConDailyDataDeck.getMileage(),70);
            }
        }else {
            calorie = calculateCalories(geConDailyDataDeck.getMileage(),70);
        }
        //插入数据
        geConDailyDataDeck.setCalorie(String.valueOf(calorie));
        geConDailyDataDeckMapper.insert(geConDailyDataDeck);

        return CommonResult.success("新增成功");
    }

    @Override
    public CommonResult getMyData(String openId) {
        MyDailyDataDeckVO myDailyDataDeckVO = new MyDailyDataDeckVO();

        //用户信息
        WxUserVO wxUserVO = new WxUserVO();
        WxUser wxUser = wxUserDao.selectOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenId, openId));
        BeanUtils.copyProperties(wxUser,wxUserVO);
        //计算注册日期
        if(wxUser.getFaceTime()!=null){
            // 计算从 pastDate 到现在的天数差
            long daysBetween = ChronoUnit.DAYS.between(wxUser.getFaceTime(), LocalDateTime.now());
            wxUserVO.setFaceDays(daysBetween);
        }else {
            wxUserVO.setFaceDays(0);
        }
        myDailyDataDeckVO.setWxUser(wxUserVO);

        //累计数据
        if(wxUser.getDeckId()!=null){
            //里程
            double sumMileage = geConDailyDataDeckMapper.getSumMileageByDeckId(wxUser.getDeckId());
            myDailyDataDeckVO.setTotalMileage(String.valueOf(sumMileage));
            //时长
            long sunDuration = geConDailyDataDeckMapper.getSumDurationByDeckId(wxUser.getDeckId());
            String totalDuration = formatSecondsToTime(sunDuration);
            myDailyDataDeckVO.setTotalDuration(totalDuration);
            //周数据
            String[] weekMileage = new String[7];
            List<String> weekDate = getWeekDate();
            for (int i=0; i<7 ;i++) {
                double dateMileage = geConDailyDataDeckMapper.getSumMileageByDeckIdAndDate(wxUser.getDeckId(),weekDate.get(i));
                weekMileage[i] = String.valueOf(dateMileage);
            }
            myDailyDataDeckVO.setWeekMileage(weekMileage);
        }else {
        myDailyDataDeckVO.setTotalMileage("0.00");
        myDailyDataDeckVO.setTotalDuration("00:00:00");
        myDailyDataDeckVO.setWeekMileage(new String[0]);
        }

        //今日记录
        MyDailyDataDeckTodayRecordVO myDailyDataDeckTodayRecordVO = new MyDailyDataDeckTodayRecordVO();
        if(wxUser.getDeckId()!=null){
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String format = now.format(formatter);
            //里程
            double sumMileage = geConDailyDataDeckMapper.getSumMileageByDeckIdAndDate(wxUser.getDeckId(),format);
            myDailyDataDeckTodayRecordVO.setTotalMileage(String.valueOf(sumMileage));
            //时长
            long sunDuration = geConDailyDataDeckMapper.getSumDurationByDeckIdAndDate(wxUser.getDeckId(),format);
            String totalDuration = formatSecondsToTime(sunDuration);
            myDailyDataDeckTodayRecordVO.setTotalDuration(totalDuration);
            //速度
            String speed = getSpeed(sunDuration, sumMileage);
            myDailyDataDeckTodayRecordVO.setSpeed(speed);
            //通过点位
            List<String> tracks = geConDailyDataDeckMapper.getTracksByDeckIdAndDate(wxUser.getDeckId(),format);
            if(tracks==null){
                myDailyDataDeckTodayRecordVO.setPassPoint(0);
            }else {
                int point= 0;
                for (String track : tracks) {
                    String[] split = track.split("#");
                    if(split.length>1){
                        point = point + split.length*2-1;
                    }else {
                        point = point + 2;
                    }
                }
                myDailyDataDeckTodayRecordVO.setPassPoint(point);
            }
        }
        myDailyDataDeckVO.setTodayRecord(myDailyDataDeckTodayRecordVO);

        //今日
        int dayOfWeek = getDayOfWeek();
        myDailyDataDeckVO.setToday(dayOfWeek);

        //天气
        JSONObject weather = geConWeatherService.getWeather();
        if(weather!=null){
            JSONObject weatherNew = weatherUtils.addLogo(weather);
            myDailyDataDeckVO.setWeather(weatherNew);
        }
        return CommonResult.success("查询成功",myDailyDataDeckVO);
    }

    @Override
    public CommonResult<List<MyDailyDataDeckSportsRecordVO>> getMySportsRecordData(String openId, Integer pageNum, Integer pageSize) {
        WxUser wxUser = wxUserDao.selectOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getOpenId, openId));

        //运动记录
        List<MyDailyDataDeckSportsRecordVO> myDailyDataDeckSportsRecordVOS = new ArrayList<>();
        if(wxUser.getDeckId()!=null){
            PageHelper.startPage(pageNum,pageSize);
            myDailyDataDeckSportsRecordVOS = geConDailyDataDeckMapper.getMySportsRecord(wxUser.getDeckId());
            for (MyDailyDataDeckSportsRecordVO myDailyDataDeckSportsRecordVO : myDailyDataDeckSportsRecordVOS) {
                //根据任务id获得里程、时长、轨迹
                MileageDurationTrackVO mileageDurationTrackVO = geConDailyDataDeckMapper.getDataByTaskId(myDailyDataDeckSportsRecordVO.getId());
                myDailyDataDeckSportsRecordVO.setMileage(mileageDurationTrackVO.getMileage());
                myDailyDataDeckSportsRecordVO.setDuration(mileageDurationTrackVO.getDuration());
                myDailyDataDeckSportsRecordVO.setTrack(mileageDurationTrackVO.getTrack());
                //时长格式化
                String duration2 = formatSecondsToTime(myDailyDataDeckSportsRecordVO.getDuration());
                myDailyDataDeckSportsRecordVO.setDuration2(duration2);
                //速度
                String speed = getSpeed(myDailyDataDeckSportsRecordVO.getDuration(), Double.parseDouble(myDailyDataDeckSportsRecordVO.getMileage()));
                myDailyDataDeckSportsRecordVO.setSpeed(speed);
                //轨迹
                String mergeTrack = mergeTrack(myDailyDataDeckSportsRecordVO.getTrack());
                String[] formatTrack = formatTrack(mergeTrack);
                myDailyDataDeckSportsRecordVO.setTrack2(formatTrack);
            }
        }
        PageInfo<MyDailyDataDeckSportsRecordVO> result = new PageInfo<>(myDailyDataDeckSportsRecordVOS);

        return CommonResult.success(String.valueOf(result.getTotal()),result.getList());

    }

    @Override
    public CommonResult getTaskDetails(String taskId) {
        //基础数据
        MyTaskDetails myTaskDetails = geConDailyDataDeckMapper.getTaskDetails(taskId);
        MileageDurationTrackVO dataByTaskId = geConDailyDataDeckMapper.getDataByTaskId(taskId);
        myTaskDetails.setMileage(dataByTaskId.getMileage());
        myTaskDetails.setDuration(String.valueOf(dataByTaskId.getDuration()));
        myTaskDetails.setCalorie(String.valueOf(dataByTaskId.getCalorie()));
        myTaskDetails.setTrack(dataByTaskId.getTrack());
        //运动时间
        String sportsTime = formatTimeRange(myTaskDetails.getBeginTime(), myTaskDetails.getEndTime());
        myTaskDetails.setSportsTime(sportsTime);
        //时长
        String duration = formatSecondsToTime(Long.parseLong(myTaskDetails.getDuration()));
        myTaskDetails.setDuration2(duration);
        //配速
        String speed = getSpeed(Long.parseLong(myTaskDetails.getDuration()), Double.parseDouble(myTaskDetails.getMileage()));
        myTaskDetails.setSpeed(speed);
        //轨迹
        String mergeTrack = mergeTrack(dataByTaskId.getTrack());
        String[] formatTrack = formatTrack(mergeTrack);
        myTaskDetails.setTrack2(formatTrack);
        //用户信息
        GeConDailyDataDeckTask geConDailyDataDeckTask = geConDailyDataDeckTaskMapper.selectById(taskId);
        WxUser wxUser = wxUserDao.getByDeckId(geConDailyDataDeckTask.getDeckId());
        myTaskDetails.setUserName(wxUser.getName());
        myTaskDetails.setUrl(wxUser.getUrl());
        return CommonResult.success("查询成功",myTaskDetails);
    }

}
